import 'package:get/get.dart';
import '../data/models/emotion_record.dart';

import '../data/repositories/emotion_repository.dart';
import '../data/repositories/emotion_repository_impl.dart';
import '../core/constants/emotion_constants.dart';
import '../core/routes/app_routes.dart';

/// 首页控制器
/// Home controller
class HomeController extends GetxController {
  // 数据仓库
  // Data repository
  final EmotionRepository _emotionRepository = EmotionRepositoryImpl();
  
  // 响应式状态变量
  // Reactive state variables
  final currentTabIndex = 0.obs;
  final todayRecords = <EmotionRecord>[].obs;
  final recentRecords = <EmotionRecord>[].obs;
  final isLoading = false.obs;
  final errorMessage = ''.obs;
  
  // 统计数据
  // Statistics data
  final totalRecords = 0.obs;
  final weekRecords = 0.obs;
  final averageIntensity = 0.0.obs;
  final mostCommonEmotion = Rx<String?>(null);
  
  @override
  void onInit() {
    super.onInit();
    loadHomeData();
  }
  
  /// 加载首页数据
  /// Load home page data
  Future<void> loadHomeData() async {
    try {
      isLoading.value = true;
      clearError();
      
      // 并行加载数据
      // Load data in parallel
      await Future.wait([
        loadTodayRecords(),
        loadRecentRecords(),
        loadStatistics(),
      ]);
      
    } catch (e) {
      setError('加载数据失败: ${e.toString()}');
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 加载今日记录
  /// Load today's records
  Future<void> loadTodayRecords() async {
    try {
      final records = await _emotionRepository.getTodayRecords();
      todayRecords.assignAll(records);
    } catch (e) {
      print('加载今日记录失败: $e');
    }
  }
  
  /// 加载最近记录
  /// Load recent records
  Future<void> loadRecentRecords() async {
    try {
      final records = await _emotionRepository.getRecentRecords(limit: 5);
      recentRecords.assignAll(records);
    } catch (e) {
      print('加载最近记录失败: $e');
    }
  }
  
  /// 加载统计数据
  /// Load statistics data
  Future<void> loadStatistics() async {
    try {
      final statistics = await _emotionRepository.getStatisticsSummary();
      totalRecords.value = statistics.totalRecords;
      weekRecords.value = statistics.weekRecords;
      averageIntensity.value = statistics.averageIntensity;
      mostCommonEmotion.value = statistics.mostCommonEmotion;
    } catch (e) {
      print('加载统计数据失败: $e');
    }
  }
  
  /// 设置当前标签页索引
  /// Set current tab index
  void setCurrentTabIndex(int index) {
    currentTabIndex.value = index;
  }
  
  /// 导航到记录页面
  /// Navigate to record page
  void navigateToRecord() {
    Get.toNamed(AppRoutes.record);
  }
  
  /// 导航到历史页面
  /// Navigate to history page
  void navigateToHistory() {
    Get.toNamed(AppRoutes.history);
  }
  
  /// 导航到分析页面
  /// Navigate to analysis page
  void navigateToAnalysis() {
    Get.toNamed(AppRoutes.analytics);
  }
  
  /// 导航到设置页面
  /// Navigate to settings page
  void navigateToSettings() {
    Get.toNamed(AppRoutes.settings);
  }
  
  /// 导航到记录详情页面
  /// Navigate to record detail page
  void navigateToRecordDetail(String recordId) {
    Get.toNamed(AppRoutes.recordDetail, arguments: {'recordId': recordId});
  }
  
  /// 刷新数据
  /// Refresh data
  Future<void> refreshData() async {
    await loadHomeData();
  }
  
  /// 获取今日情绪摘要
  /// Get today's emotion summary
  String getTodayEmotionSummary() {
    if (todayRecords.isEmpty) {
      return '今天还没有记录情绪';
    }
    
    final emotionCounts = <EmotionType, int>{};
    double totalIntensity = 0;
    
    for (final record in todayRecords) {
      emotionCounts[record.emotionType] = 
          (emotionCounts[record.emotionType] ?? 0) + 1;
      totalIntensity += record.intensity;
    }
    
    final mostCommon = emotionCounts.entries
        .reduce((a, b) => a.value > b.value ? a : b)
        .key;
    
    final avgIntensity = totalIntensity / todayRecords.length;
    
    return '今天主要情绪: ${EmotionConstants.getEmotionLabel(mostCommon.name)}, '
           '平均强度: ${avgIntensity.toStringAsFixed(1)}';
  }
  
  /// 获取本周记录趋势
  /// Get this week's record trend
  String getWeekTrend() {
    if (weekRecords.value == 0) {
      return '本周还没有记录';
    }
    
    return '本周已记录 ${weekRecords.value} 次';
  }
  
  /// 检查是否有今日记录
  /// Check if there are today's records
  bool get hasTodayRecords => todayRecords.isNotEmpty;
  
  /// 获取最近记录数量
  /// Get recent records count
  int get recentRecordsCount => recentRecords.length;
  
  /// 设置错误信息
  /// Set error message
  void setError(String message) {
    errorMessage.value = message;
  }
  
  /// 清除错误信息
  /// Clear error message
  void clearError() {
    errorMessage.value = '';
  }
}